<?php
declare (strict_types=1);

namespace app\admin\controller\tally;

use app\admin\controller\CommonController;
use app\common\model\AclUser;
use app\common\model\TallyCustom;
use app\common\model\TallyProgressDay;
use app\common\model\TallyProgressMonth;
use app\common\model\TallyTodo;
use think\db\BaseQuery;

abstract class AbstractProgressDay extends CommonController
{
    protected $modelName = TallyProgressDay::MODEL_NAME;
    protected $alias = 'd';

    protected function buildWhere(array $param): array
    {
        $where = parent::buildWhere($param);
        if (auth('roleAccounting')) {
            $where[] = ["{$this->alias}.accounting_id", '=', currentUserId()];
        }
        return $where;
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(AclUser::MODEL_NAME . ' a', "a.id={$this->alias}.accounting_id");
    }

    protected function getSearchFields(): string
    {
        $T_REPORT = TallyProgressDay::T_REPORT;
        $prefix = config('database.connections.' . config('database.default') . '.prefix');
        $tabTodo = $prefix . TallyTodo::MODEL_NAME;
        $tabMonth = $prefix . TallyProgressMonth::MODEL_NAME;
        $tabCustom = $prefix . TallyCustom::MODEL_NAME;
        return "{$this->alias}.*"
            . ",concat(a.username,a.nickname) accounting_name"
            . ",ifnull((select sum(t.estimate_time) from {$tabTodo} t where t.day_id={$this->alias}.id),0) estimate_time"
            . ",ifnull((select sum(t.actual_time) from {$tabTodo} t where t.day_id={$this->alias}.id),0) actual_time"
            . ",(case when d.type={$T_REPORT} then ifnull((select group_concat(c.name,' ',t.content,' ',t.estimate_time,'h') from {$tabTodo} t left join {$tabMonth} m on t.month_id=m.id left join {$tabCustom} c on m.custom_id=c.id where t.day_id=d.id and t.month_id!=0),'') else d.content end) _content";
    }

    protected function getSearchDefaultSort(): array
    {
        return ["{$this->alias}.progress_date" => 'asc', "{$this->alias}.type" => 'asc'];
    }
}
